// 添加商品

import { createSlice,configureStore } from "@reduxjs/toolkit";

// 2- 生成slice

const goodsSlice = createSlice({
    name: 'goods',
    initialState: {
        goodsList:[]//商品列表
    },
    reducers: {
        //名字为addGoods的reducer函数
        //第一个参数state:要修改的状态
        //第二个参数action
        addGoods(state, { payload }) {
            // playload:{goodsName:商品名字,goodsPrice:商品价格}
            state.goodsList.unlift({
                id: Math.random().toString(36).slice(2),
                ...payload
            })
        }
    }
    
})
// 2- 生成仓库
const store = configureStore({
    reducer: {
        goods:goodsSlice.reducer
    }
})

/// 3- 添加商品
//3-1
/* store.dispatch({
    type: 'goods.js/addGoods',
    payload: {
        goodsName: '手机',
        goodsPrice:12
    }
}) */
// 3-2
const { addGoods } = goodsSlice.actions;
//可以使用订阅者来订阅数据状态
const unSubscribe = store.subscribe(() => {
    //当数据状态改变后执行
    console.log(store.getStore());
    //store.subscribe函数的返回结果也是一个函数,可以通过该函数取消订阅
    unSubscribe();//取消订阅
})  
store.dispatch(addGoods({
    goodsName: '葡萄',
    goodsPrice:10
}))

store.dispatch(addGoods({
    goodsName: '苹果',
    goodsPrice:5
}))
// console.log(store.getState());
